/**
 * Created by Toma on 2016/9/13.
 * 创建一个微信密匙
 */
function onRequest(request, response, modules) {
  var http = modules.oHttp;
  var crypto = modules.oCrypto;
  var db = modules.oData;


  var nowtime = new Date().getTime();
  var datalist = ['noncestr','jsapi_ticket','timestamp','url'];

  var data = {};
      data.noncestr = 'Wm3WZYTPz0wzc2cnW';
      data.url = request.query.url;

  db.findOne({
    "table":"ticket",
    "objectId":"uG2F111n"
  },function(err,edata){
    var dataObject= JSON.parse(edata);
    data.timestamp = dataObject.last_time;
    data.jsapi_ticket = dataObject.last_ticket;
    mCache();
  });


  function mCache() {
    if(data.timestamp && nowtime <= data.timestamp + 7100*1000){
      setSignature();
    }else{
      data.timestamp = nowtime;
      oloneticket();
    }
  }



  // 获取ticket
  function oloneticket() {
    // 获取access_token
    http('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx07f1a296ba0edc13&secret=4bdc21cfd02dc47a4b6db52e48f13561', function (error, res, body) {
      if (!error && res.statusCode == 200) {
        getticket(JSON.parse(body).access_token);
      }
    });
    // 获取ticket
    function getticket(ticket){
      http('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+ticket+'&type=jsapi', function (error, res, body) {
        if (!error && res.statusCode == 200) {
          data.jsapi_ticket = JSON.parse(body).ticket;
          db.update({
            "table":"ticket",
            "objectId":"uG2F111n",
            "data":{
              "last_time": data.timestamp,
              "last_ticket": data.jsapi_ticket
            }
          },function(err,data){
            setSignature();
          });
        }
      });
    }
  }

  // 生成setSignature
  function setSignature(){
    var sig = [];
    datalist.sort().forEach(function(ele){
      sig.push(ele+'='+data[ele])
    });
    var sigstr = sig.join('&');
    var sha1 = crypto.createHash('sha1');
    sha1.update(sigstr);
    var signature = sha1.digest('hex');
    setreq(signature);
  }

  // 返回数据
  function setreq(sig){
    var req = {};
    req.timestamp = data.timestamp;
    req.nonceStr = data.noncestr;
    req.signature = sig;
    response.send(request.query.callback+"("+JSON.stringify(req)+")");
  }

}